package com.controller;

import com.conf.Constant;
import com.util.AjaxResult;
import com.util.Empty;
import com.util.UtilRandom;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;

@Slf4j
@Validated
@RestController
@Api(tags = {"首页"})
public class HomeController {

    @Value("${uploadpath}")
    String uploadpath;

    @ApiOperation("获取图片")
    @GetMapping("/getImage")
    public ResponseEntity<UrlResource> getImage(
            @ApiParam(value = "文件路径",type = "String", required = true)
            @Empty
            @RequestParam(name = "filePath",required = false) String filePath){
        log.info("图片路径【{}】",filePath);
        if(filePath.startsWith("userRes/")){
            log.info("无权限");
            return ResponseEntity.notFound().build();
        }
        try {
            Path file = Paths.get(uploadpath).resolve(filePath);
            UrlResource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok().body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    @ApiOperation("获取文件字节数组")
    @GetMapping("/getFile")
    public ResponseEntity<byte[]> getFileStream(
            @ApiParam(value = "文件路径",type = "String", required = true)
            @Empty
            @RequestParam(name = "filePath",required = false) String filePath){
        log.info("原始路径【{}】",filePath);
        if(filePath.startsWith("userRes/")){
            log.info("无权限");
            return ResponseEntity.notFound().build();
        }
        HttpHeaders headers = new HttpHeaders();
        try {
            String name = filePath.substring(filePath.lastIndexOf("/")+1);
            log.info("文件名【{}】",name);
            String path= (uploadpath+"/"+filePath.substring(0,filePath.lastIndexOf("/"))).replaceAll("/",Matcher.quoteReplacement(File.separator));
            log.info("路径【{}】",path);
            //获取文件路径
            File file = new File(path , name );
            if (file.exists()) {
                int size = (int)file.length();
                FileInputStream inputStream = new FileInputStream(file);
                byte[] bytes = new byte[size];
                int offset = 0;
                int readed;
                while(offset<size && (readed = inputStream.read(bytes, offset,inputStream.available() )) != -1){
                    offset += readed;
                }
                inputStream.close();
                headers.setContentDispositionFormData("attachment", file.getName());
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  //二进制流（或者字节数组）的形式返回
                return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("异常",e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @ApiOperation("聊天上传")
    @PostMapping(value = "/chatUpload", consumes = "multipart/form-data")
    public AjaxResult chatUpload(
            @ApiParam(hidden = true)
            @RequestAttribute(name = Constant.UserId) String user_id,
            @ApiParam(value = "文件",required = true)
            @RequestPart(name = "file") MultipartFile file){
        if(file.isEmpty()){
            return AjaxResult.getFail("文件空");
        }
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf("."));
        String folder_uri = "chat/"+user_id;
        if(Constant.listImgSuffix.contains(suffix.substring(1))){
            folder_uri = "chat/"+user_id+"/img";
        }else if(Constant.listAudioSuffix.contains(suffix.substring(1))){
            folder_uri = "chat/"+user_id+"/audio";
        }
        File folder = new File(uploadpath+File.separator+folder_uri.replaceAll("/", Matcher.quoteReplacement(File.separator)));
        if(!folder.exists()){
            folder.mkdirs();
        }
        try {
            File saveFile = new File(folder, UtilRandom.uuid()+suffix);
            file.transferTo(saveFile);
            String uri = folder_uri+"/"+saveFile.getName();
            return AjaxResult.getOk(uri);
        } catch (IOException e) {
            return AjaxResult.getFail(e.getMessage());
        }
    }

}
